package com.example.aisqlmcp.mcp.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class MCPApiKeyInterceptor implements HandlerInterceptor {
    
    private static final Logger logger = LoggerFactory.getLogger(MCPApiKeyInterceptor.class);
    
    public static final String API_KEY_HEADER = "apikey";
    public static final String API_KEY_ATTRIBUTE = "mcp.apikey";
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String apiKey = request.getHeader(API_KEY_HEADER);
        
        if (apiKey != null && !apiKey.isEmpty()) {
            logger.info("API Key found in request: {}", apiKey);
            // 将API key存储在请求属性中，供后续使用
            request.setAttribute(API_KEY_ATTRIBUTE, apiKey);
        } else {
            logger.warn("No API Key found in request");
        }
        
        return true; // 继续处理请求
    }
}